﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.customer;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Customer_Service : Base_Service, I_Customer_Service
    {
        private readonly Product_IOC _product_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Sys_IOC _sys_IOC;
        private readonly Order_IOC _order_IOC;

        public Customer_Service(Customer_IOC customer_IOC,
            Order_IOC order_IOC,
            Product_IOC product_IOC,
            Sys_IOC sys_IOC,Login_IOC login_IOC)
        {
            _product_IOC = product_IOC;
            _login_IOC = login_IOC;
            _customer_IOC = customer_IOC;
            _sys_IOC = sys_IOC;
            _order_IOC = order_IOC;

        }

        /// <summary>
        /// 新增潜在客户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Customer(AddCustomer_Dto dto,string? employeeID)
        {
            var salt = Config.GUID();
            var encryptedPassword = EncryptUtil.LoginMd5("123456", salt);
            Custom custom=new Custom() { 
           CId=Config.GenerateCustomerNo(),
           CCreateTime=DateTime.Now,
           CIsConvert=0,
           CName=dto.name,
           CPassword= encryptedPassword,
           CSalt= salt,
           CPhone=dto.phone,
           CRemark=dto.remark,
           CResource=dto.source,
           CUpdateTime=DateTime.Now,
           CStatus=0
           

            };

            _customer_IOC._customer_EFCore.Add(custom);
            _customer_IOC._customer_EFCore.SaveChanges();

            //添加跟进表
            CustomerFollow customerFollow = new CustomerFollow() { 
            CfId=Config.GenerateCustomerNo(),
            CfCreateTime=DateTime.Now,
            CfCustomerId=custom.CId,
            CfEmployeeId=employeeID,
            CfFollowContent=dto.followContent,
            CfFollowType=dto.followUp,
            CfUpdateTime=DateTime.Now,
            CfNextTime=dto.nextTime
            
            };
            _customer_IOC._customerFollow_EFCore.Add(customerFollow);
            var result = await _customer_IOC._customerFollow_EFCore.SaveChangesAsync();

            return Get_Result(result);

        }

        /// <summary>
        /// 新增跟进记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_CustomerFollow(AddCustomerFollow_Dto dto, string? id)
        {
            CustomerFollow customerFollow = new CustomerFollow() { 
            CfId=Config.GenerateCustomerNo(),
            CfCreateTime=DateTime.Now,
            CfCustomerId=dto.id,
            CfEmployeeId=id,
            CfFollowContent=dto.content,
            CfFollowType=dto.followType,
            CfNextTime=Convert.ToDateTime(dto.time),
            CfUpdateTime=DateTime.Now,
            CfResult=true
            
            };

            _customer_IOC._customerFollow_EFCore.Add(customerFollow);
            var result = await _customer_IOC._customerFollow_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 领取公海客户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Claim_The_Customer(ClaimTheCustomer_Dto dto,string? id)
        {
            //获取当前公海客户
            var data = _customer_IOC._customer_EFCore.GetAll(d => d.CId == dto.customerId).Single();
            data.CIsConvert = 0;
            data.CStatus = 0;
            data.CCreateTime=DateTime.Now;
            data.CUpdateTime = DateTime.Now;
            _customer_IOC._customer_EFCore.Update(data);
            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            //添加当前客户的跟进记录
            CustomerFollow customerFollow = new CustomerFollow() { 
            CfId=Config.GenerateCustomerNo(),
            CfResult=true,
            CfCreateTime= DateTime.Now,
            CfCustomerId = dto.customerId,
            CfEmployeeId = id,
            CfFollowContent = dto.content,
            CfFollowType = dto.followType,
            CfNextTime=Convert.ToDateTime(dto.nextFollowDate),
            CfRemark=null,
            CfUpdateTime = DateTime.Now,
           
            };
            _customer_IOC._customerFollow_EFCore.Add(customerFollow);
            var result = await _customer_IOC._customerFollow_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 完成客户跟进
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Completed_FollowUp(IsBan_Dto dto, string? id)
        {
            try
            {
                // 1. 更新客户状态
                var data = _customer_IOC._customer_EFCore.GetAll(d => d.CId == dto.id).Single();
                data.CStatus = 1;
                data.CUpdateTime = DateTime.Now;
                data.CIsConvert = 1;
                _customer_IOC._customer_EFCore.Update(data);
                await _customer_IOC._customer_EFCore.SaveChangesAsync();

                // 2. 查找客户订单总额
                var order = _order_IOC._orders_EFCore.GetAll(d => d.OCustomerId == dto.id).Sum(d => d.OTotalAmount);

                // 3. 添加VIP记录
                CustomerVip customerVip = new CustomerVip()
                {
                    CvId = Config.GUID2(),
                    CvCreateTime = DateTime.Now,
                    CvCustomerId = dto.id!,
                    CvExpireTime = null,
                    CvGetTime = DateTime.Now,
                    CvOperatorId = id ?? dto.id,
                    CvPoint = order ?? 0,
                    CvRemark = "通过跟进完成自动创建",
                    CvStatus = 1,
                    CvVipcode = $"VIP{DateTime.Now:yyyyMMddHHmmss}"
                };

                _customer_IOC._customerVip_EFCore.Add(customerVip);
                var result = await _customer_IOC._customerVip_EFCore.SaveChangesAsync();

                return Get_Result(result);
            }
            catch (DbUpdateException dbEx)
            {
                // 输出详细错误信息
                var errorMessage = dbEx.InnerException?.Message ?? dbEx.Message;
                Console.WriteLine($"数据库保存错误: {errorMessage}");
                return Get_Result(0, $"保存失败: {errorMessage}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"操作异常: {ex.Message}");
                return Get_Result(0, $"操作失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取客户的消费记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_ConsumptionRecords(string? id)
        {
            // 校验参数
            if (string.IsNullOrEmpty(id))
            {
                return Get_Result(-1, "客户ID不能为空", null);
            }

            try
            {
                // 1. 获取客户所有订单（异步查询）
                var orders = await _order_IOC._orders_EFCore
                    .GetAll(d => d.OCustomerId == id)
                    .ToListAsync();

                if (!orders.Any())
                {
                    return Get_Result(0, "该客户暂无消费记录", new List<ConsumptionRecords_Dto>());
                }

                // 2. 批量获取订单详情（避免N+1查询）
                var orderIds = orders.Select(o => o.OId).ToList();
                var orderDetails = await _order_IOC._ordersDetails_EFCore
                    .GetAll(d => orderIds.Contains(d.OdOrderId))
                    .ToListAsync();

                // 3. 预加载关联数据（一次性查询，提升性能）
                var allProductSpecs = await _product_IOC._productSpecs_EFCore.GetAll().ToListAsync(); // 产品规格（含单价）
                var allProducts = await _product_IOC._product_EFCore.GetAll().ToListAsync(); // 产品
                var allPackages = await _product_IOC._productPackage_EFCore.GetAll().ToListAsync(); // 套餐（假设表名对应）
                var allEmployees = await _login_IOC._sysEmployee_EFCore.GetAll().ToListAsync(); // 员工

                // 4. 处理订单详情，生成消费记录
                var consumptionRecords = new List<ConsumptionRecords_Dto>();

                foreach (var detail in orderDetails)
                {
                    // 关联当前详情对应的订单
                    var order = orders.FirstOrDefault(o => o.OId == detail.OdOrderId);
                    if (order == null) continue; // 跳过无效订单关联

                    // 4.1 处理产品（OdProductId为产品规格ID，可能多个用逗号分隔）
                    if (!string.IsNullOrEmpty(detail.OdProductId))
                    {
                        var productSpecIds = detail.OdProductId.Split(',', StringSplitOptions.RemoveEmptyEntries);
                        if (productSpecIds.Any())
                        {
                            // 筛选当前详情涉及的产品规格
                            var specs = allProductSpecs
                                .Where(s => productSpecIds.Contains(s.PsId))
                                .ToList();

                            foreach (var spec in specs)
                            {
                                // 关联产品信息
                                var product = allProducts.FirstOrDefault(p => p.PId == spec.PsProductId);
                                if (product == null) continue;

                                // 关联员工姓名
                                var employeeName = allEmployees
                                    .FirstOrDefault(e => e.EId == order.OEmployeeArtId)?
                                    .EName ?? "未知员工";

                                consumptionRecords.Add(new ConsumptionRecords_Dto
                                {
                                    id = order.OId,
                                    serviceName = product.PName, // 产品名称
                                    amount = spec.PsPrice, // 产品规格单价
                                    consumeTime = order.OCreateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                                    employeeID = order.OEmployeeArtId,
                                    employee = employeeName,
                                    status = order.OOrderStatus,
                                   
                                });
                            }
                        }
                    }

                    // 4.2 处理套餐（OdPackageId为套餐ID，可能多个用逗号分隔）
                    if (!string.IsNullOrEmpty(detail.OdPackageId))
                    {
                        var packageIds = detail.OdPackageId.Split(',', StringSplitOptions.RemoveEmptyEntries);
                        if (packageIds.Any())
                        {
                            // 筛选当前详情涉及的套餐
                            var packages = allPackages
                                .Where(p => packageIds.Contains(p.PpId)) // 假设套餐主键为PackageId
                                .ToList();

                            foreach (var package in packages)
                            {
                                // 关联员工姓名
                                var employeeName = allEmployees
                                    .FirstOrDefault(e => e.EId == order.OEmployeeArtId)?
                                    .EName ?? "未知员工";

                                consumptionRecords.Add(new ConsumptionRecords_Dto
                                {
                                    id = order.OId,
                                    serviceName = package.PpName, // 套餐名称（假设属性）
                                    amount = (double?)package.PpPrice, // 套餐单价（假设属性）
                                    consumeTime = order.OCreateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                                    employeeID = order.OEmployeeArtId,
                                    employee = employeeName,
                                    status = order.OOrderStatus,

                                });
                            }
                        }
                    }
                }

                // 5. 按消费时间倒序排列（最新的在前）
                var sortedRecords = consumptionRecords
                    .OrderByDescending(r => r.consumeTime)
                    .ToList();

                return Get_Result(0, "查询成功", sortedRecords);
            }
            catch (Exception ex)
            {
                // 日志记录异常（建议使用ILogger）
                return Get_Result(-1, $"查询失败：{ex.Message}", null);
            }
        }

        /// <summary>
        /// 获取客户
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Customer(Fenye_Dto dto)
        {
            var allCustomer = _customer_IOC._customerFollow_EFCore.GetAll(d => d.CfEmployeeId == dto.id).Select(d => d.CfCustomerId).ToList();
            var data =await _customer_IOC._customer_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.CCreateTime, 
                d => allCustomer.Contains(d.CId) &&  d.CName!.Contains(dto.key) && d.CIsConvert!=-1)
                .Select(d => new Customer_Dto{ 
                
                    customerNo=d.CId,
                    name=d.CName,
                    phone=d.CPhone,
                    status=d.CStatus,
                    type=d.CIsConvert,
                    sourceID=d.CResource,
                    createTime=d.CCreateTime,
                    lastFollowUp=d.CUpdateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                    
                }).ToListAsync();
            var dictionary = _sys_IOC._sysDictionary_EFCore.GetAll().ToList();
            var all = _customer_IOC._customerFollow_EFCore.GetAll().ToList();
            var currentTime = DateTime.Now; // 当前时间，用于计算30天期限
            var allVIP = _customer_IOC._customerVip_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {
                // 1. 计算创建时间是否超过30天且未转换（假设：CIsConvert=0表示未转换，1表示已转换，-1表示公海）
                // 注意：根据实际业务调整CIsConvert的原始状态值（这里假设0为未转换）
                if (d.type == 0 // 未转换
                    && d.createTime!.Value.AddDays(30) < currentTime) // 创建时间超过30天
                {
                    d.type = -1; // 标记为公共客户
                }

                // 2. 处理其他字段（保持原有逻辑）

                var customerFollows = all.Where(c => c.CfCustomerId == d.customerNo).ToList();
                d.nextTime = all.Where(c => c.CfCustomerId == d.customerNo).GroupBy(o => o.CfCreateTime).First().Select(c => c.CfNextTime).SingleOrDefault().Value.ToString("yyyy-MM-dd HH:mm:ss");
                d.cvPoint = (double?)allVIP.Where(c => c.CvCustomerId == d.customerNo).Select(c => c.CvPoint).SingleOrDefault();
                d.source = dictionary.Where(c => c.DId == d.sourceID).Select(c => c.DName).SingleOrDefault();
                d.followUpPerson = _login_IOC._sysEmployee_EFCore
                    .GetAll(c => c.EId == dto.id)
                    .Select(c => c.EName)
                    .SingleOrDefault();
            });

            var needUpdateIds = data.Where(d => d.type == -1).Select(d => d.customerNo).ToList();
            if (needUpdateIds.Any())
            {
                var customersToUpdate = await _customer_IOC._customer_EFCore
                    .GetAll(c => needUpdateIds.Contains(c.CId))
                    .ToListAsync();
                foreach (var c in customersToUpdate)
                {
                    c.CIsConvert = -1;
                }
                _customer_IOC._customer_EFCore.UpdateRange(customersToUpdate);
                await _customer_IOC._customer_EFCore.SaveChangesAsync(); // 提交更新

                var customerFllowUpdate = await _customer_IOC._customerFollow_EFCore
                    .GetAll(c => needUpdateIds.Contains(c.CfCustomerId)).ToListAsync();
                customerFllowUpdate.ForEach(c => {
                    c.CfResult = false;
                });
                _customer_IOC._customerFollow_EFCore.UpdateRange(customerFllowUpdate);
                await _customer_IOC._customerFollow_EFCore.SaveChangesAsync();//提交客户跟进记录更新
            
            }

            return Get_Result(0, "ok", new { 
            data=data,total=total,
            });
        }

        /// <summary>
        /// 获取客户的跟进状态数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Customer_Follow(string? id)
        {
            var data = await _customer_IOC._customerFollow_EFCore
                .GetAll(d => d.CfCustomerId == id && d.CfResult==true)
                .Select(d => new FollowDetails_Dto {
                    id = d.CfId,
                    customerID=d.CfCustomerId,
                    content = d.CfFollowContent,
                    employeeID=d.CfEmployeeId,
                    time = d.CfUpdateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).ToListAsync();
            var customer = _customer_IOC._customer_EFCore.GetAll().ToList();
            var employee = _login_IOC._sysEmployee_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.status = customer.Where(c => c.CId == d.customerID).Select(c => c.CStatus).Single();
                d.follower = employee.Where(c => c.EId == d.employeeID).Select(c => c.EName).Single();
            });

            return Get_Result(0,"ok",data);
        }

        /// <summary>
        /// 获取所有的公海客户
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_HightSeasCustomer(Fenye_Dto dto)
        {
           var data=await _customer_IOC._customer_EFCore
                .GetAll(out int total,dto.page,dto.limit,false,o=>o.CCreateTime,
                d=>
                d.CIsConvert==-1
                &&
                (d.CName!.Contains(dto.key) || d.CPhone!.Contains(dto.key)) && d.CResource.Contains(dto.source))
                .Select(d => new HightSeasCustomer_Dto{ 
                id=d.CId,
                name=d.CName,
                phone=d.CPhone,
                sourceID=d.CResource,
                status="待跟进",
                createTime=d.CCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                lastContact=d.CUpdateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                })
                .ToListAsync();

            var all = _sys_IOC._sysDictionary_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.source = all.Where(c => c.DId == d.sourceID).Select(c => c.DName).SingleOrDefault();
            });

            return Get_Result(0, "ok", new { 
            data=data,
            total=total
            });
        }
    }
}
